package com.wanxi.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wanxi.VO.LeaveVO;
import com.wanxi.dao.LeaveDao;
import com.wanxi.dto.ResultDTO;
import com.wanxi.entity.LeaveEntity;
import com.wanxi.service.LeaveService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : 林子淳
 * @create 2023/3/2 11:07
 */
@Service("leaveService")
public class LeaveServiceImpl implements LeaveService<LeaveVO> {
    @Autowired
    LeaveDao leaveDao;
    @Autowired
    LeaveEntity leaveEntity;

    Jedis jedis = new Jedis();
    @Override
    public ResultDTO delete(LeaveVO leaveVO) {
//        LeaveEntity leaveEntity = new LeaveEntity();
        BeanUtils.copyProperties(leaveVO,leaveEntity);
        int delete = leaveDao.delete(leaveEntity);
        jedis.del("leaveList");
        return ResultDTO.getResult(delete);
    }

    @Override
    public ResultDTO findAll(LeaveVO leaveVO) {
//        LeaveEntity leaveEntity = new LeaveEntity();
        ObjectMapper mapper = new ObjectMapper();
        BeanUtils.copyProperties(leaveVO,leaveEntity);
        int count = leaveDao.count();
        List<LeaveEntity> list = new ArrayList<>();
        if (leaveEntity.getPage() !=null && leaveEntity.getPage()==1 && jedis.exists("leaveList")){
            String jedisLeaveList = jedis.get("leaveList");
            JavaType javaType = mapper.getTypeFactory().constructParametricType(List.class, LeaveEntity.class);
            try {
                list = mapper.readValue(jedisLeaveList,javaType);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }else{
            list = leaveDao.findAll(leaveEntity);
            try {
                String leaveList = mapper.writeValueAsString(list);
                jedis.set("leaveList",leaveList);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }

        return ResultDTO.getResult("", count, list);
    }


}
